#include<iostream>
#include<unistd.h>
#include<vector>
#include<time.h>
#include<semaphore.h>

// //获取随机数
// int&& date()
// {
//     srand((unsigned int)time(NULL));

//     int num = 10 + rand() % 90;
//     return 10 + rand() % 90;
// }

//最大容量
#define MAX 5

template<class T>
class cycle_p_c
{
public:
    cycle_p_c()
    {
        //开缓存空间
        _buffer.resize(MAX);
        //锁
        pthread_mutex_init(&p_mutex,NULL);
        pthread_mutex_init(&c_mutex,NULL);
        //信号量
        sem_init(&p_message,0,MAX);
        sem_init(&c_message,0,0);
        //下标
        tail=0;
        head=0;
    }
    ~cycle_p_c()
    {
        pthread_mutex_destroy(&p_mutex);
        pthread_mutex_destroy(&c_mutex);
        sem_destroy(&p_message);
        sem_destroy(&c_message);
    }
    //生产
    void push_back(const T& date)
    {
        //看信号量是否足够(生产信号量-1)
        sem_wait(&p_message);
        //此时说明已经申请到信号量
        pthread_mutex_lock(&p_mutex);
        
        //生产
        head%=MAX;
        _buffer[head++]=date;
        //消费信号量+1
        sem_post(&c_message);

        std::cout<<"我生产了:"<<date<<std::endl;
        
        pthread_mutex_unlock(&p_mutex);
    }
    //消费
    void pop()
    {
        //看信号量是否足够(消费信号量-1)
        sem_wait(&c_message);
        //此时说明已经申请到信号量
        pthread_mutex_lock(&c_mutex);
        
        //消费
        std::cout<<"我消费了:"<<_buffer[tail]<<"...."<<std::endl;
        _buffer[tail++]=0;
        //生产信号量+1
        sem_post(&p_message);
        
        pthread_mutex_unlock(&c_mutex);
    }
private:
    //数据缓存
    std::vector<T> _buffer;
    //信号变量*2
    sem_t p_message;
    sem_t c_message;
    //两个下标
    size_t head;
    size_t tail;
    //两个互斥锁(确保每次只有一个生产和一个消费并发执行)
    pthread_mutex_t p_mutex;
    pthread_mutex_t c_mutex;
};